package com.example.gugongticket.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.example.gugongticket.dao.UserRepository;
import com.example.gugongticket.entity.Orders;
import com.example.gugongticket.entity.SalesStatistics;
import com.example.gugongticket.entity.Ticket;
import com.example.gugongticket.entity.User;
import com.example.gugongticket.service.TicketSalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class TicketSalesController {

    @Autowired
    private TicketSalesService ticketSalesService;

    @Autowired
    private UserRepository userRepository;


    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, String>> registerUser(@RequestParam String username, @RequestParam String password,
                                                            @RequestParam String email, @RequestParam String phone) {
        List<User> existingUsers = userRepository.findByUsername(username);
        if (!existingUsers.isEmpty()) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "该用户名已存在");
            return ResponseEntity.badRequest().body(response);
        }
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setEmail(email);
        newUser.setPhone(phone);
        userRepository.save(newUser);
        Map<String, String> successResponse = new HashMap<>();
        successResponse.put("message", "注册成功");
        return ResponseEntity.ok(successResponse);
    }

    // 用户登录
//    @PostMapping("/login")
//    public ResponseEntity<Map<String, String>> login(@RequestParam String username, @RequestParam String password) {
//        boolean isLoginSuccessful = ticketSalesService.login(username, password);
//        if (isLoginSuccessful) {
//            Map<String, String> response = new HashMap<>();
//            response.put("message", "登录成功");
//            return ResponseEntity.ok(response);
//        } else {
//            Map<String, String> response = new HashMap<>();
//            response.put("message", "登录失败");
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
//        }
//    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, String>> login(@RequestParam String username, @RequestParam String password) {
        int isLoginSuccessful = ticketSalesService.login(username, password);
        if (isLoginSuccessful==0) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "0");
            return ResponseEntity.ok(response);
        } else if(isLoginSuccessful==1){
            Map<String, String> response = new HashMap<>();
            response.put("message", "1");
            return ResponseEntity.ok(response);
        }else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "2");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    // 订大门票
    @PostMapping("/book/gate")
    public ResponseEntity<Object> bookGateTickets(@RequestParam int userId, @RequestParam int quantity,
                                                  @RequestParam double totalPrice, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        try {
            ticketSalesService.bookGateTickets(userId, quantity, totalPrice, date);
            return ResponseEntity.ok().body("{\"message\":\"预订成功\"}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\":\"预订失败：" + e.getMessage() + "\"}");
        }
    }

    // 订馆中馆门票
    @PostMapping("/book/exhibition")
    public ResponseEntity<Object>  bookExhibitionTickets(@RequestParam int userId, @RequestParam String type,
                                      @RequestParam int quantity, @RequestParam double totalPrice,
                                      @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        Ticket.TicketType ticketType = Ticket.TicketType.valueOf(type);

        try {
            ticketSalesService.bookExhibitionTickets(userId, ticketType, quantity, totalPrice, date);
            return ResponseEntity.ok().body("{\"message\":\"预订成功\"}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\":\"预订失败：" + e.getMessage() + "\"}");
        }
    }

    // 退票
    @PutMapping("/refund/{OrdersId}")
    public String refundTicket(@PathVariable int OrdersId) {
        try {
            ticketSalesService.refundTicket(OrdersId);
            return "退票成功";
        } catch (Exception e) {
            return "退票失败";
        }
    }




    // 查询订票记录
    @GetMapping("/booking-records/{userId}")
    public List<Orders> getBookingRecords(@PathVariable int userId) {
        return ticketSalesService.getBookingRecords(userId);
    }

    // 查询每日余票
    @GetMapping("/daily-remaining/{type}")
    public int getDailyRemainingTickets(@PathVariable String type) {
        Ticket.TicketType ticketType = Ticket.TicketType.valueOf(type);
        return ticketSalesService.getDailyRemainingTickets(ticketType);
    }



    //管理员逻辑
    // 查询游客信息
    @GetMapping("/users")
    public List<User> findUsersByOptions(@RequestParam String option, @RequestParam String value) {

            return ticketSalesService.findUsersByOptions(option, value);

    }

    // 查询每日售票数据
    @GetMapping("/daily-sales-statistics")
    public List<SalesStatistics> getDailySalesStatistics(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {

        // 获取单个 SalesStatistics 对象
        return ticketSalesService.getDailySalesStatistics(date);

    }

    // 查询每月售票数据
    @GetMapping("/monthly-sales-statistics")
    public List<SalesStatistics> getMonthlySalesStatistics(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd")Date endDate) {
        return ticketSalesService.getMonthlySalesStatistics(startDate, endDate);
    }

    // 查询每年售票数据
    @GetMapping("/yearly-sales-statistics")
    public List<SalesStatistics> getYearlySalesStatistics(@RequestParam int year) {
        return ticketSalesService.getYearlySalesStatistics(year);
    }

    // 统计营业数据
    @GetMapping("/total-sales")
    public double getTotalSales() {
        return ticketSalesService.getTotalSales();
    }

    // 插入每天每种门票的余票数据
    @PostMapping("/insert-daily-ticket-data")
    public String insertDailyTicketData(@RequestParam String type, @RequestParam int quantity) {
        try {
            Ticket.TicketType ticketType = Ticket.TicketType.valueOf(type);
            ticketSalesService.insertDailyTicketData(ticketType, quantity);
            return "修改成功";
        } catch (Exception e) {
            return "修改失败";
        }
    }
}